const mysql = require('mysql2');
const {database} = require('../config/database');

const pool = mysql.createPool({
    ...database,
    connectionLimit: 10
});

const query = function (sql, values) {
    return new Promise((resolve, reject) => {
        pool.getConnection(function (err, connection) {
            if (err) {
                resolve({
                    code: 500,
                    msg: `数据库连接失败：${err}`
                })
            } else {
                connection.query(sql, values, (err, results) => {
                    if (err) {
                        resolve({
                            code: 400,
                            msg: `语句错误：${err}`
                        })
                    } else {
                        resolve({
                            code: 200,
                            data: results
                        });
                    }
                    connection.release();//释放线程池
                })
            }
        })
    });
};

module.exports = {
    query,
    escape: mysql.escape//用于防止sql注入攻击
};